import axios from "axios";
import path from 'path'
import fs from 'fs'

const fn = (time: number) => new Promise((resolve) => {
    setTimeout(() => {
        resolve(time)
    }, time)
})

// TODO qps 10
export const fyFetchApi = async (text: string, to: string = 'en', contextConfig: ContextType) => {
    const token = await getFetchToken(false, contextConfig)
    try {
        const { data } = await axios({
            url: `https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=${token}`,
            method: "POST",
            data: {
                from: "auto",
                to: to,
                q: text,
            },
        });
        if (!data?.result?.trans_result) {
            console.log('err', data);
        }
        return data?.result?.trans_result;
    } catch (error) {
        throw error
    }
};



async function requestToken(contextConfig: ContextType) {
    const { data } = await axios({
        url: "https://aip.baidubce.com/oauth/2.0/token",
        method: "post",
        headers: {
            "Content-Type": "application/json",
        },
        data: {},
        params: {
            client_id: contextConfig.translate?.bd?.clientId,
            client_secret: contextConfig.translate?.bd?.clientSecret,
            grant_type: contextConfig.translate?.bd?.grantType,
        },
    });
    return data;
}

const getFetchToken = async (force: boolean = false, contextConfig: ContextType) => {
    const catchDir = path.join(process.cwd(), ".catch");
    fs.existsSync(catchDir) || fs.mkdirSync(catchDir);
    if (fs.existsSync(path.join(catchDir, "./fy-token"))) {
        const data = JSON.parse(fs.readFileSync(path.join(catchDir, "./fy-token"), "utf-8"));
        if (data.expire > parseInt(String(new Date().getTime() / 1000)) && !force) {
            return data.token;
        }
    }
    const data = await requestToken(contextConfig);
    if (data.access_token) {
        fs.writeFileSync(
            path.join(catchDir, "./fy-token"),
            JSON.stringify({
                token: data.access_token,
                expire: parseInt(String(new Date().getTime() / 1000)) * 1 + data.expires_in,
            })
        );
        return data.access_token;
    } else {
        throw new Error(data)
    }
};